"""
工具函数
"""

import json
import os
from typing import Dict, Any
from tqsdk import TqAuth


def load_config(config_path: str) -> Dict[str, Any]:
    """加载配置文件"""
    if not os.path.exists(config_path):
        return {}
    
    with open(config_path, 'r', encoding='utf-8') as f:
        return json.load(f)


def get_auth_from_config(config_dir: str = "config") -> TqAuth:
    """从配置获取认证信息"""
    accounts_file = os.path.join(config_dir, "accounts.json")
    accounts = load_config(accounts_file)
    
    tqsdk_account = accounts.get("tqsdk_account", {})
    
    return TqAuth(
        tqsdk_account.get("user_id", ""),
        tqsdk_account.get("password", "")
    )


def calculate_performance_metrics(equity_curve: list) -> Dict[str, float]:
    """计算性能指标"""
    if len(equity_curve) < 2:
        return {
            'total_return': 0,
            'max_drawdown': 0,
            'sharpe_ratio': 0
        }
    
    import pandas as pd
    import numpy as np
    
    equity = pd.Series(equity_curve)
    returns = equity.pct_change().dropna()
    
    # 总收益率
    total_return = (equity.iloc[-1] / equity.iloc[0] - 1) * 100
    
    # 最大回撤
    peak = equity.expanding().max()
    drawdown = (equity - peak) / peak * 100
    max_drawdown = abs(drawdown.min())
    
    # 夏普比率
    if returns.std() > 0:
        sharpe_ratio = returns.mean() / returns.std() * np.sqrt(252)
    else:
        sharpe_ratio = 0
    
    return {
        'total_return': round(total_return, 2),
        'max_drawdown': round(max_drawdown, 2),
        'sharpe_ratio': round(sharpe_ratio, 2)
    }